'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import type { Category, Post, PostPageResult } from '@/lib/index'
import {
  Pagination 
} from 'antd';
import { useRouter, useSearchParams } from 'next/navigation';
import { EyeOutlined, LikeOutlined } from '@ant-design/icons'

// 分类过滤器组件
function CategoryFilter({ 
  categories,
  activeCategory, 
  onChange,
}: { 
  categories: Category[]
  activeCategory: Category['id'] | 0
  onChange: (categoryId: Category['id'] | 0) => void 
}) {
  const router = useRouter();
  // 处理分类点击事件
  const handleCategoryClick = (categoryId: Category['id']) => {
    onChange(categoryId)
    
    // 构建新的 URL 参数
    const params = new URLSearchParams()

    if(categoryId){
      params.set('categoryId', categoryId.toString())
    }
    // 重置到第一页
    params.set('page', '1')
    
    // 跳转到新的 URL
    router.push(`/posts?${params.toString()}`)
  }

  return (
    <div className="mb-8 flex flex-wrap gap-2">
      <button
        onClick={() => handleCategoryClick(0)}
        className={`px-4 py-2 rounded-full text-sm transition-colors ${
          !activeCategory
            ? 'bg-blue-600 text-white'
            : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
        }`}
      >
        全部
      </button>
      {
        categories?.map((category: any) => (
            <button
              key={category.id}
              onClick={() => handleCategoryClick(category.id)}
              className={`px-4 py-2 rounded-full text-sm transition-colors ${
                activeCategory === category.id
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
              }`}
            >
              {category.name}
            </button>
        ))
      }
    </div>
  )
}

// 文章列表组件
function PostList({ posts }: { posts: Post[] }) {
  return (
    <div className="grid gap-6">
      {posts.map((post) => (
        <article key={post.id} className="p-4 md:p-6 bg-white dark:bg-gray-800 rounded-lg shadow">
          <h2 className="text-2xl font-semibold mb-2">
            <Link href={`/posts/${post.id}`} className="hover:text-blue-600 dark:text-white dark:hover:text-blue-400">
              {post.title}
            </Link>
          </h2>
          <div className="mb-2">
            <span className="text-sm bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 px-2 py-1 rounded">
              {post.category?.name}
            </span>
          </div>
          <p className="text-gray-600 dark:text-gray-300">{post.description}</p>
          <div className="mt-4 flex gap-2">
            {post.tags.map((tag, index) => (
              <span key={`${post.id}-${tag}-${index}`} className="text-sm bg-gray-100 dark:bg-gray-700 dark:text-gray-300 px-2 py-1 rounded">
                {tag}
              </span>
            ))}
          </div>
          <div className="flex gap-2 mt-2 text-sm text-gray-500 dark:text-gray-400">
            <span>发布于 {post.created_at}</span>
            {/* 浏览量 */}
            <span className="flex gap-1 ml-2">
              <EyeOutlined />
              {post.views}
            </span>
            {/* 点赞数 */}
            <span className="flex gap-1 ml-2">
              <LikeOutlined />
              {post.likes}
            </span>
          </div>
        </article>
      ))}
    </div>
  )
}

// 带过滤功能的文章列表
export default function FilteredPosts({ postPage,categories }: { postPage: PostPageResult,categories: Category[] }) {
  const [activeCategory, setActiveCategory] = useState<Category['id'] | 0>(0)
  const filteredPosts: Post[] = postPage.posts
  
  const router = useRouter()
  const searchParams = useSearchParams()

  const currentCategory = searchParams.get('categoryId') || 0

  useEffect(() => {
    if (currentCategory) {
      setActiveCategory(parseInt(currentCategory))
    }
  }, [currentCategory])
  return (
    <>
      <CategoryFilter
        categories={categories}
        activeCategory={activeCategory}
        onChange={setActiveCategory}
      />
      {filteredPosts.length > 0 ? (
        <PostList posts={filteredPosts} />
      ) : (
        <div className="text-center text-gray-500 dark:text-gray-400 py-8">
          暂无文章
        </div>
      )}
      {/* 分页器 */}
      <Pagination
        className='flex justify-center'
        style={{ marginTop: '40px' }}
        showLessItems
        total={postPage.total}
        current={postPage.page}
        pageSize={postPage.pageSize}
        onChange={(page: any) => {
          router.push(`/posts?page=${page}`)
        }}
        showSizeChanger={false}
        hideOnSinglePage
        // showTotal={(total: any, range: any) => `共 ${total} 条`}
      />
    </>
  )
} 